<?php

/**
 * 订单支付
 */

namespace app\order\middle;


class PayMiddle extends \app\base\middle\BaseMiddle {


    protected function base() {
        $orderNo = html_clear($this->params['order_no']);
        $this->params['user_id'] = intval($this->params['user_id']);
        if (empty($orderNo)) {
            return $this->stop('订单号不存在!', 404);
        }

        $orderNo = urldecode($orderNo);
        $orderNos = explode('|', $orderNo);
        $orderNo = implode('|', $orderNos);

        foreach ($orderNos as $key => $vo) {
            $orderNos[$key] = int_format($vo);
        }

        if (empty($orderNos)) {
            return $this->stop('订单不能存在!');
        }

        $where = [];
        $where['_sql'] = 'order_no in(' . implode(',', $orderNos) . ')';
        $orderList = target('order/Order')->LoadList($where);

        if (empty($orderList)) {
            return $this->stop('订单不存在!');
        }

        $orderPrice = 0;
        $deliveryPrice = 0;
        $orderSum = 0;
        $orderIds = [];
        $currency = [];

        foreach ($orderList as $key => $vo) {
            if ($vo['pay_status'] || !$vo['order_status'] || $vo['order_user_id'] <> $this->params['user_id']) {
                unset($orderList[$key]);
                continue;
            }
            $orderIds[] = $vo['order_id'];
            $orderPrice += $vo['order_price'];
            $deliveryPrice += $vo['delivery_price'];
            $orderSum += $vo['order_sum'];

            foreach ($vo['order_currency'] as $k => $v) {
                $currency[$k] = $v;
                $currency[$k]['amount'] = $v['amount'];
                $currency[$k]['cost'] = $v['cost'];
                $currency[$k]['decimal'] = $v['decimal'];
                $currency[$k]['money'] = $v['money'];
                $currency[$k]['name'] = $v['name'];
                $currency[$k]['unit'] = $v['unit'];
                $currency[$k]['type'] = $v['type'];
            }
        }

        if (empty($orderList)) {
            return $this->stop('提交付款的订单无效!');
        }
        arsort($orderIds);

        $orderIds = implode(',', $orderIds);
        $totalPrice = price_calculate($orderPrice, '+', $deliveryPrice);
        $orderPrice = price_format($orderPrice);
        $deliveryPrice = price_format($deliveryPrice);

        $currencyList = target('member/MemberCurrency')->typeList();

        foreach ($currencyList as $key => $vo) {
            if (empty($currency[$key])) {
                unset($currencyList[$key]);
                continue;
            }
            $currencyList[$key]['amount'] = target($vo['target'], 'service')->amountAccount($this->params['user_id']);
        }

        $payList = target('member/PayConfig')->typeList(true, $this->params['platform']);

        return $this->run([
            'currency' => $currency,
            'orderNo' => $orderNo,
            'orderList' => $orderList,
            'payList' => $payList,
            'currencyList' => $currencyList,
            'totalPrice' => $totalPrice,
            'orderPrice' => $orderPrice,
            'deliveryPrice' => $deliveryPrice,
            'orderSum' => $orderSum,
            'orderIds' => $orderIds,
        ]);

    }

    protected function info() {
        $orderGoods = target('order/OrderGoods')->loadList([
            '_sql' => 'order_id in (' . $this->data['orderIds'] . ')'
        ]);
        $orderGroup = [];
        foreach ($orderGoods as $key => $vo) {
            $orderGroup[$vo['order_id']][] = $vo;
        }
        $orderList = $this->data['orderList'];
        foreach ($orderList as $key => $vo) {
            $orderList[$key]['order_items'] = $orderGroup[$vo['order_id']];
        }

        return $this->run([
            'orderList' => $orderList
        ]);
    }

    protected function pay() {
        $type = html_clear($this->params['type']);
        $target = target('order/Order');

        //创建临时合并支付订单
        $orderPayNo = target('order/Order', 'service')->addPay($this->params['user_id'], $this->data['orderIds']);
        if (!$orderPayNo) {
            return $this->stop(target('order/Order', 'service')->getError());
        }
        $sign = data_sign($orderPayNo);
        $target->beginTransaction();

        $postCurrency = $this->params['currency'];
        $postCurrency = $postCurrency ? $postCurrency : [];


        //代币支付
        $currencyPay = [];
        foreach ($this->data['currency'] as $key => $vo) {
            if ($vo['pay_status']) {
                continue;
            }
            if ($vo['type']) {
                if (!in_array($key, $postCurrency)) {
                    $this->data['totalPrice'] += $vo['money'];
                    continue;
                }
            } else {
                if (!in_array($key, $postCurrency)) {
                    return $this->stop('请选择货币支付方式');
                }
            }
            if ($vo['amount'] <= 0) {
                continue;
            }
            if (!target($this->data['currencyList'][$key]['target'], 'service')->decAccount($this->params['user_id'], $vo['amount'], '账户支付',  $this->data['orderNo'], '订单支付扣款')) {
                return $this->stop(target($this->data['currencyList'][$key]['target'], 'service')->getError());
            }
            $currencyPay[] = $key;
        }

        //完成代币支付状态
        if ($currencyPay) {
            foreach ($this->data['orderList'] as $key => $vo) {
                $orderCurrency = $vo['order_currency'];
                foreach ($vo['order_currency'] as $k => $v) {
                    if (in_array($k, $currencyPay)) {
                        $orderCurrency[$k]['pay_status'] = 1;
                        if ($v['type']) {
                            $orderCurrency[$k]['pay_type'] = 1;
                        }
                    }
                }
                if (!$target->edit(['order_id' => $vo['order_id'], 'order_currency' => serialize($orderCurrency)])) {
                    return $this->stop($target->getError());
                }
            }
        }
        $target->commit();


        if (bccomp($this->data['totalPrice'], 0, 2) !== 1 || empty($type)) {
            $type = 'system';
        }

        $target->beginTransaction();

        $payList = target('member/PayConfig')->typeList();
        $payTypeInfo = $payList[$type];
        if (empty($payTypeInfo)) {
            return $this->stop('该支付类型不存在!');
        }
        $curInfo = reset($this->data['orderList']);
        $title = $curInfo['order_title'];

        $data = target($payTypeInfo['target'], 'pay')->getData([
            'user_id' => $this->params['user_id'],
            'order_no' => $orderPayNo,
            'money' => $this->data['totalPrice'],
            'title' => $title,
            'body' => $title,
            'app' => 'order',
        ], url('complete', ['pay_no' => $orderPayNo, 'pay_sign' => $sign]));
        if (!$data) {
            $target->rollBack();

            return $this->stop(target($payTypeInfo['target'], 'pay')->getError());
        }
        $target->commit();
        return $this->run(['type' => $type, 'complete' => isset($data['complete']) ? $data['complete'] : 0, 'data' => $data], '即将进行支付中!');
    }

    protected function complete() {
        $payNo = $this->params['pay_no'];
        $paySign = $this->params['pay_sign'];
        if (empty($payNo) || empty($paySign)) {
            return $this->stop('页面不存在', 404);
        }
        if (!data_sign_has($payNo, $paySign)) {
            return $this->stop('页面不存在', 404);
        }

        $name = '支付成功';
        $desc = '支付已完成，请等待订单处理!';

        $list = hook('service', 'Type', 'PayComplete');
        $data = [];
        foreach ($list as $value) {
            $data = array_merge_recursive((array)$data, (array)$value);
        }

        return $this->run([
            'status' => 1,
            'name' => $name,
            'desc' => $desc,
            'payNo' => $payNo,
            'paySign' => $paySign,
            'hookList' => $data
        ]);
    }

}